<template>
  <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible" fullscreen
    center append-to-body>
    <el-form class="verify-form" :model="dataForm" :rules="dataRule" ref="dataForm" label-width="80px">
      <el-row>
        <el-col :span="6">
          <el-form-item label="促销活动名称" prop="promotionTitle" label-width="100px">
            <el-input v-model="dataForm.promotionTitle" placeholder="促销活动名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="创建时间" prop="createTime">
            <el-input v-model="dataForm.createTime" placeholder="创建时间" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="生效时间" prop="startTime">
            <el-date-picker style="width: 100%;" v-model="dataForm.startTime" type="date" value-format="yyyy-MM-dd"
              placeholder="选择日期"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="截至时间" prop="endTime">
            <el-date-picker style="width: 100%;" v-model="dataForm.endTime" type="date" value-format="yyyy-MM-dd"
              placeholder="选择日期"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="memo">
        <el-input type="textarea" v-model="dataForm.memo" placeholder="备注"></el-input>
      </el-form-item>

      <el-row>
        <el-col :span="21">
          <el-form-item label="查询部门">
            <el-input type="textarea" v-model="dataForm.deptName" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label-width="0">
            <el-button size="mini" @click="openDeptDialog">选择</el-button>
          </el-form-item>
        </el-col>
      </el-row>

      <el-tabs type="border-card">
        <el-tab-pane label="参与活动品种">
          <el-divider content-position="left">活动品种信息</el-divider>
          <el-row>
            <el-col :span="12">
              <el-button type="primary" icon="el-icon-plus" @click.prevent="addRow()">添加活动品种信息</el-button>
              <el-button type="primary" icon="el-icon-delete" @click.prevent="delData()">删除</el-button>
            </el-col>
          </el-row>
          <div class="avue-crud">
            <el-table :data="this.dataForm.details" border @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="ctgId" label="商品类别">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.ctgId" disabled>
                    <el-option v-for="item in ctgOption" :value="item.id" :label="item.name" :key="item.id"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="saleCtgId" label="商品销售类别">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.saleCtgId" @change="getCtgId(scope.row,scope.$index)">
                    <el-option v-for="item in saleCtgOption" :value="item.id" :label="item.name" :key="item.id"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="supplyName" label="商品制造商" width="300">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.supplyName" readonly>
                    <el-button slot="append" type="primary" @click="supplySearchHandle(scope.row)">选择</el-button>
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column prop="brandName" label="商品品种" width="300">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.brandName" readonly @change="getPriceInfo(scope.row,scope.$index)">
                    <el-button slot="append" type="primary" @click="brandSearchHandle(scope.row)">选择</el-button>
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column prop="spec" label="商品型号">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.spec" @change="getPrice(scope.row,scope.$index)" v-if="!(scope.row.saleCtgId == '3' || scope.row.saleCtgId == '5')"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="originalPrice" label="该品种商品原价"></el-table-column>
              <el-table-column prop="promotionPrice" label="促销价格">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.promotionPrice"></el-input>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <search-dept v-if="deptVisible" ref="deptDialog" @refreshData="getDeptData"></search-dept>
    <!-- 弹窗，查询制造商 -->
    <search-supply v-if="supplyVisible" ref="supplyDialog" @refreshData="getSupplyData"></search-supply>
    <!-- 弹窗，查询商品品种 -->
    <search-brand v-if="brandVisible" ref="brandDialog" @refreshData="getBrandData"></search-brand>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit" :loading="ischeck" v-prevent-re-click>确定</el-button>
      <el-switch v-model="dataForm.auditStatus" active-text="保存并审核" :inactive-value="0" :active-value="1" style="margin-left: 15px;"></el-switch>
    </span>
  </el-dialog>
</template>

<script>
  import { getEimsPromotionObj, addEimsPromotionObj, putEimsPromotionObj } from '@/api/eims/promotion'
  import SearchDept from './SearchDept'
  import { getCtgList, getSaleCtgList, getSaleCtgInfo } from '@/api/eims/ctg'
  import SearchSupply from './SearchSupply'
  import SearchBrand from './SearchBrand'
  import { getBrandPrice, getBrandPrice2 } from '@/api/eims/goods-price'

  import { mapGetters } from 'Vuex'
  export default {
    data() {
      return {
        visible: false,
        ischeck: false,
        deptVisible: false,
        supplyVisible: false,
        brandVisible: false,
        dataForm: {
          id: 0,
          promotionTitle: '',
          startTime: '',
          endTime: '',
          auditStatus: 0,
          auditUser: '',
          stopTime: '',
          stopUser: '',
          memo: '',
          deptName: '',
          depts: [],
          details: []
        },
        saleCtgOption: [],
        dataRule: {
          promotionTitle: [{
            required: true,
            message: '促销活动名称不能为空',
            trigger: 'blur'
          }],
          startTime: [{
            required: true,
            message: '生效时间不能为空',
            trigger: 'blur'
          }],
          endTime: [{
            required: true,
            message: '结束时间不能为空',
            trigger: 'blur'
          }],
          auditStatus: [{
            required: true,
            message: '审核状态(1-已审核,0-未审核)不能为空',
            trigger: 'blur'
          }]
        }
      }
    },
    created() {
      this.timeFormate(new Date());
      this.getCtgList();
      this.getSaleCtgList()
    },
    computed: {
      ...mapGetters(['userInfo', 'bizData'])
    },
    components: {
      SearchDept,
      SearchSupply,
      SearchBrand,
    },
    methods: {
      init(id) {
        this.dataForm.id = id || 0
        if (!this.dataForm.id) {
          this.timeFormate(new Date());
          this.dataForm.deptName = ''
          this.dataForm.depts = []
          this.dataForm.details = []
        }

        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            getEimsPromotionObj(this.dataForm.id).then(response => {
              if(response.data.code == '0'){
                this.dataForm = response.data.data
                this.dataForm.details = response.data.data.details
                this.dataForm.depts = response.data.data.depts
                let names = []
                this.dataForm.depts.forEach(item => {
                  names.push(item.deptName)
                })
                this.dataForm.deptName = names.join(',')
              }else{
                this.$message.error(response.data.msg)
              }
            })
          }
        })
      },
      //  获取商品类型列表
      getCtgList() {
        getCtgList().then(response => {
          if(response.data.code == '0'){
            this.ctgOption = response.data.data
          }else{
            this.$message.error(response.data.msg)
          }

        })
      },
      getSaleCtgList() {
        getSaleCtgList().then(response => {
          if(response.data.code == '0'){
            this.saleCtgOption = response.data.data
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      getCtgId(data, index) {
        getSaleCtgInfo(data.saleCtgId).then(response => {
          if(response.data.code == '0'){
            this.$set(this.dataForm.details[index], 'ctgId', response.data.data.ctgId)
            this.$set(this.dataForm.details[index], 'supplyName', '')
            this.$set(this.dataForm.details[index], 'supplyId', '')
            this.$set(this.dataForm.details[index], 'brandName', '')
            this.$set(this.dataForm.details[index], 'brandId', '')
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      //显示当前时间（年月日时分秒）
      timeFormate(timeStamp) {
        let year = new Date(timeStamp).getFullYear();
        let month = new Date(timeStamp).getMonth() + 1 < 10 ? "0" + (new Date(timeStamp).getMonth() + 1) : new Date(
          timeStamp).getMonth() + 1;
        let date = new Date(timeStamp).getDate() < 10 ? "0" + new Date(timeStamp).getDate() : new Date(timeStamp).getDate();
        let hh = new Date(timeStamp).getHours() < 10 ? "0" + new Date(timeStamp).getHours() : new Date(timeStamp).getHours();
        let mm = new Date(timeStamp).getMinutes() < 10 ? "0" + new Date(timeStamp).getMinutes() : new Date(timeStamp).getMinutes();
        let ss = new Date(timeStamp).getSeconds() < 10 ? "0" + new Date(timeStamp).getSeconds() : new Date(timeStamp).getSeconds();
        this.nowTime = "POUT" + year + "" + month + "" + date + "" + hh + "" + mm + "" + ss + this.dataForm.deptId;
        this.dataForm.createTime = year + "-" + month + "-" + date;
      },
      addRow() {
        var timestamp = new Date().getTime()
        var list = {
          timestamp: timestamp,
          saleCtgId: '',
          supplyName: '',
          supplyId: '',
          brandName: '',
          brandId: '',
          spec: '',
          originalPrice: '',
          promotionPrice: '',
          memo: ''
        };
        this.dataForm.details.push(list)
      },
      //  删除
      delData() {
        let arr = this.dataForm.details.filter(item => {
          let result = this.selectlistRow.some(rowItem => {
            if (rowItem.timestamp == item.timestamp) {
              return true
            }
          })
          if (!result) {
            return item
          }
        })
        this.dataForm.details = [...arr]
      },
      // 表单提交
      dataFormSubmit() {
        this.ischeck = true
        this.dataForm.createTime = ""
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            if (this.dataForm.id) {
              putEimsPromotionObj(this.dataForm).then(response => {
                if(response.data.code == '0'){
                  this.$message.success('修改成功')
                  this.visible = false
                  this.$emit('refreshDataList')
                }else{
                  this.$message.error(response.data.msg)
                }
                this.ischeck = false
              }).catch(() => {
                this.ischeck = false
              })
            } else {
              addEimsPromotionObj(this.dataForm).then(response => {
                if(response.data.code == '0'){
                  this.$message.success('添加成功')
                  this.visible = false
                  this.$emit('refreshDataList')
                }else{
                  this.$message.error(response.data.msg)
                }
                this.ischeck = false
              }).catch(() => {
                this.ischeck = false
              })
            }
          }else{
            this.ischeck = false
          }
        })
      },
      // 选择事件 得到选中的数据
      handleSelectionChange(data) {
        this.selectlistRow = data
      },
      //  打开查询部门弹窗
      openDeptDialog() {
        this.deptVisible = true
        this.$nextTick(() => {
          this.$refs.deptDialog.init()
        })
      },
      //  获取选择部门数据
      getDeptData(data) {
        this.dataForm.depts = []
        let names = []
        if (data.length) {
          data.forEach(item => {
            let info = {
              deptId: item.id,
              deptName: item.name
            }
            names.push(item.name)
            this.dataForm.depts.push(info)
          })
        }
        this.dataForm.deptName = names.join(',')
      },
      //  查询制造商信息
      supplySearchHandle(data) {
        this.supplyVisible = true
        let ctgId = data.ctgId || ''
        let info = {
          ctgId: ctgId,
          data: data
        }
        this.$nextTick(() => {
          this.$refs.supplyDialog.init(info)
        })
      },
      //  获取制造商信息
      getSupplyData(data) {
        this.dataForm.details.forEach((item, index) => {
          if (item.timestamp == data.timestamp) {
            this.dataForm.details[index].supplyId = data.supplyId
            this.dataForm.details[index].supplyName = data.supplyName
          }
        })
      },
      //  查询商品品种信息
      brandSearchHandle(data) {
        this.brandVisible = true
        let ctgId = data.ctgId || ''
        let supplyId = data.supplyId || ''
        if (!supplyId) {
          this.$message.warning('请选择制造商')
          return
        }
        let info = {
          ctgId: ctgId,
          supplyId: supplyId,
          data: data
        }
        this.$nextTick(() => {
          this.$refs.brandDialog.init(info)
        })
      },
      //  获取商品品种信息
      getBrandData(data) {
        this.dataForm.details.forEach((item, index) => {
          if (item.timestamp == data.timestamp) {
            this.dataForm.details[index].brandId = data.brandId
            this.dataForm.details[index].brandName = data.brandName
            let info = this.dataForm.details[index]
            if (info.saleCtgId == 3 || info.saleCtgId == 5) {
              getBrandPrice2(info.saleCtgId, info.supplyId, info.brandId).then(response => {
                if(response.data.code == '0'){
                  this.$set(this.dataForm.details[index], 'originalPrice', response.data.data.price)
                }else{
                  this.$message.error(response.data.data.msg)
                }
              })
            }
          }
        })
      },
      //获取原价格(成品片使用)
      getPriceInfo(data, index) {
        if (data.saleCtgId == 3 || data.saleCtgId == 5) {
          getBrandPrice(data.saleCtgId, data.supplyId, data.brandId, data.spec).then(response => {
            if(response.data.data.code == '0'){
              this.$set(this.dataForm.details[index], 'originalPrice', response.data.data.price)
            }else{
              this.$message.error(response.data.data.msg)
            }
          })
        }

      },
      //获取原价格
      getPrice(data, index) {
        if (!data.brandId) {
          this.$message.warning('请选择制造商')
        }
        if (!data.spec) {
          this.$message.warning('请输入批号')
        }
        getBrandPrice(data.saleCtgId, data.supplyId, data.brandId, data.spec).then(response => {
          if(response.data.data.code == '0'){
            this.$set(this.dataForm.details[index], 'originalPrice', response.data.data.price)
          }else{
            this.$message.error(response.data.data.msg)
          }
        })
      }
    }
  }
</script>
